package com.wangzhixuan.controller;

import com.wangzhixuan.db.bean.Department;
import com.wangzhixuan.service.DepartmentService;
import com.wangzhixuan.util.HttpUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by dell on 2017/2/28.
 */
@Controller
@RequestMapping(value = "/")
public class DepartmentController {
    @Autowired
    private DepartmentService departmentService;
    @ResponseBody
    @RequestMapping(value = "/departIcon.img",method = RequestMethod.GET,produces = MediaType.IMAGE_PNG_VALUE)
    public byte[] seeicon(@RequestParam("departmentId")Long departmentId, HttpServletRequest request, HttpServletResponse response){
        Department department=departmentService.getDepartmentById(departmentId);
        byte[] icon = null;
        try {
            if (department != null) {
                icon = department.getIcon();
                if (icon == null) {
                    String defaultImg = "/static/images/default-icon.jpg";
                    InputStream in = this.getClass().getClassLoader().getResourceAsStream(defaultImg);
                    icon = IOUtils.toByteArray(in);
                }
                response.setContentType("image/png");
                OutputStream stream;
                stream = response.getOutputStream();
                stream.write(icon);
                stream.flush();
                stream.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return icon;
    }
}
